/*
 * Project: Set Sample
 * Copyright (C) 2013 alf.labs gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.alflabs.setsample.model;

import com.alflabs.annotations.NonNull;

import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

public class SetSolution implements Comparable<SetSolution> {
    public static int N = 3;
    public final SetCard mCards[] = new SetCard[N];
    public final String mDescription;

    public SetSolution(SetCard c1, SetCard c2, SetCard c3) {
        mCards[0] = c1;
        mCards[1] = c2;
        mCards[2] = c3;
        Arrays.sort(mCards);
        mDescription = SetCard.describeSet(c1, c2, c3);
    }

    @SuppressWarnings("SimplifiableIfStatement")
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o instanceof SetSolution) {
            SetSolution s = (SetSolution) o;

            Set<SetCard> s3 = new TreeSet<SetCard>();
            s3.add(s.mCards[0]);
            s3.add(s.mCards[1]);
            s3.add(s.mCards[2]);
            if (!s3.remove(mCards[0])) return false;
            if (!s3.remove(mCards[1])) return false;
            if (!s3.remove(mCards[2])) return false;
            return s3.isEmpty();
        }

        return false;
    }

    @Override
    public int hashCode() {
        long v = (long) mCards[0].hashCode() * (long) mCards[1].hashCode() * (long) mCards[2].hashCode();
        // transform long into 32-bit int hashcode using Android Long.hashCode() implementation's idea.
        return (int) (v ^ (v >>> 32));
    }

    @Override
    public int compareTo(@NonNull SetSolution another) {
        return hashCode() - another.hashCode();
    }

    /** Representation for debugging. */
    @Override
    @NonNull
    public String toString() {
        return "<SetSolution " + Arrays.toString(mCards) + '>';
    }
}
